<template>
  <div>
    <a-drawer
      :title="title"
      :maskClosable="true"
      :width="drawerWidth"
      placement="right"
      :closable="true"
      @close="handleCancel"
      :visible="visible"
      destroyOnClose
      style="height: 100%;">

      <a-spin :spinning="confirmLoading">
        <j-form-container>
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                  <a-input placeholder="请输入姓名" v-model="model.name" :disabled="disabledFlag"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="phone">
                  <a-input placeholder="请输入电话" v-model="model.phone" :disabled="disabledFlag"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="微信号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="phone">
                  <a-input placeholder="请输入微信号" v-model="model.wechatNumber"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="客源渠道" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerChannel">
                  <j-dict-select-tag
                    placeholder="请选择客源渠道"
                    dictCode="customer_info_customer_channel"
                    v-model="model.customerChannel"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="小区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currentChooseArea">
                  <a-input v-model="currentChooseArea" readOnly  @click="changeArea()" placeholder="请选择所在地区" :disabled="disabledFlag"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="项目地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <!--<a-input-number v-model="building" style="width: 25%" @change="validateAddress" :disabled="disabledFlag"></a-input-number>&nbsp;栋&nbsp;
                  <a-input-number v-model="unit" style="width: 25%" @change="validateAddress" :disabled="disabledFlag"></a-input-number>&nbsp;单元&nbsp;
                  <a-input-number v-model="room" style="width: 25%" @change="validateAddress" :disabled="disabledFlag"></a-input-number>&nbsp;室&nbsp;<br>
                  <div class="ant-form-explain" style="margin-bottom: -20px;color: red" v-if="addressFlag">{{addressErrorMsg}}</div>-->
                  <a-input v-model="model.address" placeholder="请输入项目地址"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="装修风格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="decorationStyle">
                  <j-dict-select-tag
                    placeholder="请输入装修风格"
                    dictCode="gh_customer_info_decoration_style"
                    v-model="model.decorationStyle"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="房屋户型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="houseType">
                  <j-dict-select-tag
                    placeholder="请选择房屋户型"
                    dictCode="customer_info_house_type"
                    v-model="model.houseType"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="房屋面积" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="houseArea">
                  <a-input-number v-model="model.houseArea" style="width: 100%" :min="0" placeholder="请输入房屋面积"></a-input-number>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="VR全景图链接" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="panoramaUrl">
                  <a-input v-model="model.panoramaUrl" style="width: 100%" :min="0" placeholder="请输入VR全景图链接"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="量房时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="calculateTime">
                  <j-date placeholder="请选择量房时间" :disabled="model.calculateTime != null" v-model="model.calculateTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <a-col :span="24">
                <a-form-model-item label="邀约到店时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inviteTime">
                  <j-date placeholder="请选择邀约到店时间" :disabled="model.inviteTime != null" v-model="model.inviteTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <a-col :span="24">
                <a-form-model-item label="实际到店时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="factTime">
                  <j-date placeholder="请选择邀约到店时间" :disabled-date="disabledFactTime" :disabled="model.factTime != null" v-model="model.factTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <a-col :span="24">
                <a-form-model-item label="交定时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="decidesTime">
                  <j-date placeholder="请选择交定时间" :disabled-date="disabledFactTime" :disabled="model.decidesTime != null" v-model="model.decidesTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <a-col :span="24">
                <a-form-model-item label="签约时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signedTime">
                  <j-date placeholder="请选择签约时间" :disabled-date="disabledFactTime" :disabled="model.signedTime != null" v-model="model.signedTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <!--<a-col :span="24">
                <a-form-model-item label="开工时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startworkTime">
                  <j-date placeholder="请选择开工时间"  v-model="model.startworkTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>

              <a-col :span="24">
                <a-form-model-item label="竣工时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="completionTime">
                  <j-date placeholder="请选择竣工时间"  v-model="model.completionTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-model-item>
              </a-col>-->

              <a-col :span="24">
                <center>
                  <a-button type="primary" style="width: 100%" @click="handleOk">保存</a-button>
                </center>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-spin>
    </a-drawer>
    <map-container ref="mapContainer" @ok="selectedArea($event)"></map-container>
  </div>
</template>

<script>
  import { duplicateCheck } from '@/api/api'
  import { getAction, putAction } from '@/api/manage'
  import MapContainer from "../../../../../../components/amap/MapContainer";
  import moment from 'moment'

  export default {
    name: "editCustomerInfoModal",
    components: {
      MapContainer
    },
    data () {
      return {
        disabledFlag: false,
        modalWidth: 300,
        drawerWidth: '100%',
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        modaltoggleFlag: true,
        confirmDirty: false,
        disableSubmit: false,
        departIdShow: false,
        title: "编辑客户资料",
        visible: false,
        uploadLoading: false,
        confirmLoading: false,
        model: {},
        previewVisible: false,
        previewImage: '',
        areaOptions: [],
        currentChooseArea: '',
        poi: {},
        dataFields: {
          label: 'name',
          key: 'id',
          value: 'code',
          children: "children"
        },
        url: {
          edit: "/ghCustomerInfo/edit",
          querySharingOfficerList: '/ghSharingOfficer/queryList',
          queryAddressInfoList: "/ghAddressInfo/queryAllList",
          isSignContractUrl: "/ghCustomerInfo/isSignContractUrl",
          checkAddressExist: "/ghCustomerInfo/checkAddressExist",
        },
        validatorRules: {
          name: [{ required: true, message: '客户姓名不能为空' }],
          address: [{ required: true, message: '项目地址不能为空' }],
          houseArea: [{ required: true, message: '房屋面积不能为空' }],
          houseType: [{ required: true, message: '请选择房屋户型' }],
        },
        building: '',
        unit: '',
        room: '',
        addressFlag:false,
        addressErrorMsg:'',
      }
    },
    methods: {
      edit(record){
        this.model = Object.assign({}, record);
        this.currentChooseArea = "";
        if (record.provinceCode){
          this.currentChooseArea += record.provinceCode;
        }
        if (record.cityCode){
          this.currentChooseArea += record.cityCode;
        }
        if (record.areaCode){
          this.currentChooseArea += record.areaCode;
        }
        if (record.townshipCode){
          this.currentChooseArea += record.townshipCode;
        }
        if (record.villageCode){
          this.currentChooseArea += record.villageCode;
        }
        /*if (record.address != null && record.address !== ""){
          if (record.address.indexOf("栋") !== -1){
            this.building = record.address.substring(0,record.address.indexOf("栋"));
          }
          if (record.address.indexOf("单元") !== -1){
            if (record.address.indexOf("栋") !== -1){
              this.unit = record.address.substring(record.address.indexOf("栋")+1,record.address.indexOf("单元"))
            }else {
              this.unit = record.address.substring(0,record.address.indexOf("单元"))
            }
          }
          if (record.address.indexOf("室") !== -1){
            if (record.address.indexOf("单元") !== -1){
              this.room = record.address.substring(record.address.indexOf("单元")+2,record.address.indexOf("室"));
            }else if (record.address.indexOf("栋") !== -1){
              this.room = record.address.substring(record.address.indexOf("栋")+1,record.address.indexOf("室"));
            }else {
              this.room = record.address.substring(0,record.address.indexOf("室"));
            }
          }
        }
        this.validateAddress()*/
        this.visible = true;
        this.initSharingOfficerList();
        this.isSignContract(record.id);
      },
      //查询客户是否创建签署合同（意向购买或者客户合同）
      isSignContract(customerId){
        getAction(this.url.isSignContractUrl,{customerId:customerId}).then(res=>{
          if(res.success){
            if (res.result.length > 0){
              this.disabledFlag = true;
            }
          }
        })
      },
      handleOk () {
        /*let address = "";
        if (this.building != null && this.building !== '' && this.building !== 0){
          address += this.building + "栋";
        }else {
          this.$message.warning("请输入楼栋号")
          return;
        }
        if (this.unit != null && this.unit !== '' && this.unit !== 0){
          address += this.unit + "单元";
        }
        if (this.room != null && this.room !== '' && this.room !== 0){
          address += this.room + "室";
        }else {
          this.$message.warning("请输入房间号")
          return;
        }*/
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            if (that.poi != null){
              that.model.provinceCode = that.poi.province;
              that.model.cityCode = that.poi.city;
              that.model.areaCode = that.poi.district;
              that.model.townshipCode = this.poi.township;
              that.model.villageCode = this.poi.village;
              that.model.lng = that.poi.lng;
              that.model.lat = that.poi.lat;
              //that.model.address = address;
            }
            putAction(that.url.edit,that.model).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('editOk');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
        /*if (!this.addressFlag){

        }*/
      },
      //窗口最大化切换
      toggleScreen(){
        if(this.modaltoggleFlag){
          this.modalWidth = window.innerWidth;
        } else {
          this.modalWidth = 300;
        }
        this.modaltoggleFlag = !this.modaltoggleFlag;
      },
      close () {
        this.visible = false;
        this.disableSubmit = false;
        this.nextDepartOptions = [];
        this.departIdShow = false;
        this.building = "";
        this.unit = "";
        this.room = "";
      },
      handleCancel () {
        this.close()
      },
      initSharingOfficerList(){
        getAction(this.url.querySharingOfficerList).then(res=>{
          if(res.success){
            this.sharingOfficerOptions = res.result;
          }
        })
      },
      changeArea(){
        this.$refs.mapContainer.title = "选择小区"
        this.$refs.mapContainer.visible = true;
        this.$refs.mapContainer.init(this.model.lng, this.model.lat, this.model.address);
      },
      selectedArea(params) {
        this.poi = params;
        this.currentChooseArea = params.address;
      },
      validatePhone(rule, value, callback){
        if(!value){
          callback()
        }else{
          if(new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)){
            let params = {
              tableName: 'gh_customer_info',
              fieldName: 'phone',
              fieldVal: value,
              dataId: this.customerId,
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback("手机号已存在!")
              }
            })
          }else{
            callback("请输入正确格式的手机号码!");
          }
        }
      },
      validateAddress(){
        let address = this.currentChooseArea;
        if (this.building == null || this.building === "" || this.building === 0){
          this.addressErrorMsg = "请输入楼栋号";
          this.addressFlag = true;
          return;
        }else {
          this.addressFlag = false;
          address += this.building + "栋"
        }
        if (this.unit != null || this.unit !== "" || this.unit !== 0){
          address += this.unit + "单元"
        }
        if (this.room == null || this.room === "" || this.room === 0){
          this.addressErrorMsg = "请输入房间号";
          this.addressFlag = true;
          return;
        }else {
          this.addressFlag = false;
          address += this.room + "室"
        }
        const that = this;
        getAction(this.url.checkAddressExist,{address: address}).then(res=>{
          if(res.success){
            that.addressFlag = false;
          }else {
            that.addressErrorMsg = "当前项目地址已存在";
            that.addressFlag = true;
          }
        })
      },
      disabledFactTime(current){
        return current < moment().subtract(1, 'days').endOf('day') || current > moment().subtract(0, 'days').endOf('day')
      },
    }
  }
</script>

<style scoped>
  .avatar-uploader > .ant-upload {
    width:104px;
    height:104px;
  }
  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td{
    padding-top:10px;
    padding-bottom:10px;
  }

  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

  /*【JTC-502】 添加用户两个滚动条*/
  /deep/ .ant-drawer-body {
    padding-bottom: 53px;
  }

</style>
